﻿using System;
using System.Windows.Input;

namespace MVVM.ViewModel {
    public class ViewCommand:ICommand {

        #region Microsoft pattern implementation for ICommand
        /// <summary>
        /// Execution logic
        /// </summary>
        readonly Action<object> _execute;
        /// <summary>
        /// Status of the execution logic
        /// </summary>
        readonly Predicate<object> _canExecute;
        /// <summary>
        /// Create a command that execute always
        /// </summary>
        /// <param name="execute">The action</param>
        public ViewCommand(Action<object> execute):this(execute,null) {

        }
        /// <summary>
        /// Create a new command and verify if executable
        /// </summary>
        /// <param name="execute">The action</param>
        /// <param name="canExecute">Status of execution logic</param>
        public ViewCommand(Action<object> execute, Predicate<object> canExecute) {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }
        #endregion

        #region ICommand Members

        public bool CanExecute(object parameter) {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter) {
            _execute(parameter);
        }

        #endregion
    }
}
